package com.rrd.hive.udf.plist.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：Jason
 * @date ：Created in 2023/10/25 2:43 PM
 * @description：
 * @modified By：
 * @version: 1.0
 */
public class PlistCommon {

    public static Configuration config() {
        System.setProperty("HADOOP_USER_NAME", "hdfs");
        Configuration conf = new Configuration();
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        return conf;
    }
    public static String loadDataFromFile(String filePath) throws IOException {
        FileSystem fs = FileSystem.newInstance(URI.create(filePath), config());
        Path remotePath = new Path(filePath);
        if (fs.exists(remotePath)) {
            FSDataInputStream in = fs.open(remotePath);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            try {
                byte[] b = new byte[1024];
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                while(in.read(b) != -1){
                    out.write(b);
                }
                return String.valueOf(out);
            } finally {
                bufferedReader.close();
                in.close();
                fs.close();
            }
        } else {
            System.out.println("找不到指定的文件");
            return null;
        }
    }

    public static boolean hiveUdfRegExp(String input, String pattern) {
        if (input == null) return false;
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(input);
        if (matcher.find(0)) {
            return true;
        }
        return false;
    }

    public static void isExits(Map<String,String> map, String name, String tag) {
        if (map.containsKey(name)) {
            final String s1 = map.get(name);
            final String newTag = s1 + "#" + tag;
            map.put(name, newTag);
        } else {
            map.put(name, tag);
        }
    }
}
